package com.loooooo.pm2024.modules.search;


import com.loooooo.pm2024.data.Result;
import com.loooooo.pm2024.modules.pm.model.Issue;
import monad.mmseg.analysis.MMSegAnalyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.*;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.*;
import org.apache.lucene.store.FSDirectory;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class IssueIndexer {

    static MMSegAnalyzer analyzer = new MMSegAnalyzer();


    public static void index(List<Issue> issueList, String indexFolder) throws IOException {
        File dir = new File(indexFolder);
        if (!dir.exists()) dir.mkdirs();

        //Creating an Lucene IndexWriter
        IndexWriterConfig conf = new IndexWriterConfig(analyzer);
        IndexWriter iw = new IndexWriter(FSDirectory.open(Paths.get(indexFolder)), conf);
        //Iterating through images building the low level features

        for (Issue issue : issueList) {
            String text = String.format("%s,%s", issue.getSubject(), issue.getContent());
            Document document = new Document();
            Field idField = new StringField("id", issue.getId() + "", Field.Store.YES);
            Field subField = new StringField("subject", issue.getSubject(), Field.Store.YES);
            Field statusField = new StringField("status", issue.getStatus() + "", Field.Store.YES);
            Field hungField = new StringField("hung", issue.getHung() + "", Field.Store.YES);
            Field contentField = new TextField("content", String.format("%s,%s", issue.getSubject(), issue.getContent()), Field.Store.YES);
            document.add(idField);
            document.add(subField);
            document.add(statusField);
            document.add(hungField);
            document.add(contentField);
            //iw.addDocument(document);
            iw.updateDocument(new Term("id", issue.getId() + ""), document);
        }
        //closing the IndexWriter
        iw.close();
        System.out.println("Finished indexing.");
    }


    public static Result search(String keyword, String indexFolder) {
        IndexReader indexReader = null;
        try {
            indexReader = StandardDirectoryReader.open(FSDirectory.open(Paths.get(indexFolder)));
            IndexSearcher searcher = new IndexSearcher(indexReader);
            QueryParser queryParser = new QueryParser("content", analyzer);
            Query q = queryParser.parse(keyword);
            TopDocs topDocs = searcher.search(q, 10);
            System.out.println(topDocs.totalHits);
            ScoreDoc[] scoreDocs = topDocs.scoreDocs;

            QueryScorer scorer = new QueryScorer(q);
            Result result = Result.success().set("total", topDocs.totalHits.value);

            List<String> idList = new ArrayList<>();


            for (ScoreDoc scoreDoc : scoreDocs) {
                Document document = searcher.doc(scoreDoc.doc);
                idList.add(document.get("id"));
            }
            result.setData(idList);
            return result;

        } catch (Exception e) {
            return Result.error(10500, e.getMessage());
        }


    }
}
